package handler;

import bean.UserInfo;
import context.ComServerContext;
import enums.MessageTypeEnum;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import message.LoginMessage;
import message.Message;

@ChannelHandler.Sharable
public class ComServerInboundChannelHandler extends SimpleChannelInboundHandler<Message> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ComServerContext.comContext().addChannelCacheByChannelId(ctx.channel().id().asShortText(), ctx.channel());
        System.out.println("客户端连接成功，地址：" + ctx.channel().remoteAddress() + " ID：" + ctx.channel().id().asShortText());
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
    }

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, Message msg) throws Exception {
        System.out.println(msg);
        if(MessageTypeEnum.LOGIN.getCode().equals(msg.getType())){
            // TODO 验证用户名密码

            ((LoginMessage) msg).getUserInfo().setLogin(true);
            ((LoginMessage) msg).setLogin(true);
            UserInfo userInfo = ((LoginMessage) msg).getUserInfo();
            // 登陆成功添加到缓存
            ComServerContext.comContext().addChannelCacheByUserId(userInfo, ctx.channel());
            //给客户端返回消息
            ComServerContext.comContext()
                    .serverSendMessageToClientByClientId(msg, ctx.channel().id().asShortText());

            System.out.println(userInfo.getUId() + "登陆成功");
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 当出现异常就关闭连接
        cause.printStackTrace();
        ctx.close();
    }


}
